﻿/* JavaScript Document
Version 1.3

Thanit@, Suparerk@
- 1.3 use Menu ID instead Menu Index
- fix bug Click on top menu
- fix bug เมื่อรีโหลดด้วย ajax
- no limit Level
sample data
{
    "data": [
	{ "id" : "b1", "caption" : "Menu1", "link" : null, "icon" : null, "child" : [
		{ "id" : "b11", "caption" : "Menu1.1", "link" : null, "icon" : null, "child" : null },
		{ "id" : "b12", "caption" : "Menu1.2", "link" : null, "icon" : null, "child" : null },
		{ "id" : "b13", "caption" : "Menu1.3", "link" : null, "icon" : null, "child" : null },
		{ "id" : "b14", "caption" : "Menu1.4", "link" : null, "icon" : null, "child" : null }
	]
	},
	{ "id" : "b2", "caption" : "Menu2", "link" : null, "icon" : null, "child" : [
		{ "id" : "b21", "caption" : "Menu2.1", "link" : null, "icon" : null, "child" : null },
		{ "id" : "b22", "caption" : "Menu2.2", "link" : null, "icon" : null, "child" : null },
		{ "id" : "b23", "caption" : "Menu2.3", "link" : null, "icon" : null, "child" : null },
		{ "id" : "b24", "caption" : "Menu2.4", "link" : null, "icon" : null, "child" : null }
	]
   	 },
	{ "id" : "b3", "caption" : "Menu3", "link" : null, "icon" : null, "child" : [
		{ "id" : "b31", "caption" : "Menu3.1", "link" : null, "icon" : null, "child" : null },
		{ "id" : "b32", "caption" : "Menu3.2", "link" : null, "icon" : null, "child" : null },
		{ "id" : "b33", "caption" : "Menu3.3", "link" : null, "icon" : null, "child" : null },
		{ "id" : "b34", "caption" : "Menu3.4", "link" : null, "icon" : null, "child" : null }
	]
	},
	{ "id" : "b4", "caption" : "Menu4", "link" : null, "icon" : null, "child" : [
		{ "id" : "b41", "caption" : "Menu4.1", "link" : null, "icon" : null, "child" : null },
		{ "id" : "b42", "caption" : "Menu4.2", "link" : null, "icon" : null, "child" : null },
		{ "id" : "b43", "caption" : "Menu4.3", "link" : null, "icon" : null, "child" : null}
	]
    	},
	{ "id" : "b5", "caption" : "Menu5", "link" : null, "icon" : null, "child" : null}
    ]
}

CSS (ui.topMenu.css)

*/

(function($) {

    ///Menu Builder
    jQuery.fn.topMenu = function(settings) {
        var defaults = { dataURL: "topmenudata.txt", menuActive: null, submenuWidth: 200, menuAlign: 'right'}// menuActive คือ ตำแหน่งของหัวข้อปัจจุบัน
        var options = jQuery.extend(defaults, settings);

        var fixLayOut;
        var holder = $(this);

        $.getJSON(options.dataURL, function(data) {	 //build mark up tag

            var menuObj = data.data;
            var indexActive = 0;
            holder.html("");
            $(menuObj).each(function(i) {
                // create parent menu


                holder.append('<span index="' + indexActive + '" id="' + menuObj[i].id.toString() + '" class="topMenu ui-state-default ui-corner-top" style="float:' + options.menuAlign + '" menuname="' + menuObj[i].caption.toString() + '"></span>');
                // check link url
                if (menuObj[i].link != null) { // have link
                    $("span#" + menuObj[i].id.toString()).append(menuObj[i].caption.toString());
                    $("span#" + menuObj[i].id.toString()).click(function() {
                        window.location = menuObj[i].link.toString();
                    });
                } else { //not have link
                    $("span#" + menuObj[i].id.toString()).append(menuObj[i].caption.toString());
                }

                var subPix;
                if (options.submenuWidth != 'auto') {
                    subPix = "px"
                } else {
                    subPix = "";
                }


                if (menuObj[i].child != null) {
                    // create child menu
                    $('span#' + menuObj[i].id.toString()).append('<div id="subMenu' + menuObj[i].id.toString() + '" class="subMenu" style="width:' + options.submenuWidth + subPix + '"><ul class="ui-state-default ui-state-hover ui-corner-bottom"></ul></div>');

                    $(menuObj[i].child).each(function(d) {

                        if (menuObj[i].child[d].child != null) {
                            // create sub of child menu
                            $('span#' + menuObj[i].id.toString() + ' ul:first').append('<li id="hasSub' + menuObj[i].child[d].id + '" class="hasSubmenu"><a href="#">' + menuObj[i].child[d].caption.toString() + '</a></li>');
                            $('li#hasSub' + menuObj[i].child[d].id).append('<div id="subSubMenu' + menuObj[i].child[d].id + '" class="subMenu subSubMenu" style="width:' + options.submenuWidth + subPix + '"; left:50px;"><ul class="ui-state-default ui-state-hover ui-corner-all"></ul></div>');

                            var Opener = $(this);
                            var Selector = $("#subSubMenu" + menuObj[i].child[d].id); //make Selector

                            Selector.data("Opener", 'li#hasSub' + menuObj[i].child[d].id);

                            $('li#hasSub' + menuObj[i].child[d].id).hover(function(e) {
                                e.stopPropagation();
                                e.cancelBubble = true;
                                $(".subSubMenu").hide();

                                if (options.submenuWidth != 'auto') {
                                    fixLayOut = Number(options.submenuWidth);
                                } else {
                                    fixLayOut = $(this).width();
                                }
                                //alert(fixLayOut);
                                //
                                //alert(window.document.width);
                                $(Selector).appendTo("body");
                                //alert($(this).offset().left + fixLayOut + ":" + $(document).width());
                                if ($(this).offset().left + fixLayOut < $(document).width() - 40) {
                                    Selector.css({ "top": $(this).offset().top + 10 + "px", "left": $(this).offset().left+fixLayOut-10 + "px" }).show('slide', { direction: 'left' }, 500);
                                } else {
									//alert()
                                    Selector.css({ "top": $(this).offset().top + 10 + "px", "left": $(this).offset().left -fixLayOut + "px" }).show('slide', { direction: 'right' }, 500);
                                }

                            }).prepend('<div class="ui-icon ui-icon-triangle-1-e" style="float:right"></div>');

                            $(".subSubMenu").hover(function(e) {
                                e.stopPropagation();
                                e.cancelBubble = true;
                            });


                            $(menuObj[i].child[d].child).each(function(f) {
                                if (menuObj[i].child[d].child[f].link != null) { // have link
                                    var linkURL = menuObj[i].child[d].child[f].link.toString();
                                } else { //not have link
                                    var linkURL = "#";
                                }
                                $('div#subSubMenu' + menuObj[i].child[d].id + ' ul').append('<li><a href="' + linkURL + '">' + menuObj[i].child[d].child[f].caption.toString() + '</a></li>');
                            });
                        } else {
                            if (menuObj[i].child[d].link != null) { // have link
                                var linkURL = menuObj[i].child[d].link.toString();
                            } else { //not have link
                                var linkURL = "#";
                            }
                            $('span#' + menuObj[i].id.toString() + ' ul').append('<li><a href="' + linkURL + '">' + menuObj[i].child[d].caption.toString() + '</a></li>');
                        }


                    });
                }
                indexActive++;
            });

            //build menu 
            $("span.topMenu").disableSelection()
            holder.find("span.topMenu").click(function(e) {
                e.stopPropagation();
                e.cancelBubble = true;


                killMenu();

                if ($(this).find(".subMenu").css("display") == "none") {

                    var topPadding = $(this).css("padding-top");
                    var bottomPadding = $(this).css("padding-bottom");
                    var thisPadding = Number(topPadding.substring(0, topPadding.length - 2)) + Number(bottomPadding.substring(0, bottomPadding.length - 2)); //get topMenu Item padding top-bot

                    var Opener = $(this);
                    var Selector = $("body").find("#subMenu" + $(this).attr("id")); //make Selector

                    if (options.submenuWidth != 'auto') {
                        fixLayOut = options.submenuWidth;
                    } else {
                        fixLayOut = $(this).find(".subMenu").width();
                    }

                    $(this).find("#subMenu" + $(this).attr("id")).appendTo("body"); //append to body for IE posion fix

                    Selector.css("top", $(this).offset().top + $(this).height() + thisPadding);
                    if ($(this).offset().left + Selector.width() + 8 > $(window).width()) {//if menu stack window width
                        Selector.css("left", $(this).offset().left + $(this).width() - fixLayOut + horizonPaddingSize($(this)));
                        //horizonPaddingSize() form tw.API
                    } else {
                        var tmpBorder = $(this).css("border-left-width");
                        tmpBorder = Number(tmpBorder.substring(0, tmpBorder.length - 2))
                        Selector.css("left", $(this).offset().left - (tmpBorder * 2));
                    }


                    Selector.show('slide', { direction: 'up' }, 500, function() {
                        $(this).data("Opener", Opener); //make Openner
                        //alert($(this).data("Opener").attr("id"));
                    });
                };

                //return false;
            });
            //finalize 
            //topmenu hover
            $("span.topMenu").hover(function() {
                $(this).removeClass("ui-state-default").addClass("ui-state-hover");
            }, function() {
                $(this).removeClass("ui-state-hover").addClass("ui-state-default");
            });
            //click on li space highlight
            $(".subMenu ul li").click(function() {

                if ($(this).children("a").attr("href") != "#") {
                    window.location.href = $(this).children("a").attr("href");
                }

            });
            //find active menu
            // $("span#"+options.menuActive).removeClass("ui-state-default").addClass("ui-state-active");
            $("span.topMenu").eq(options.menuActive).removeClass("ui-state-default").addClass("ui-state-active");
            //restore menu
            $(document).click(function() {// kill all menu which are Open when click to space
                killMenu();
            });

            //end finalize 
        });

        function killMenu() {
            $("div.subMenu").each(function(i) {

                if ($(this).data("Opener")) {
                    //alert($($(this).data("Opener")).attr('id'))
                    $(".subSubMenu").hide(50, function() {
                        $(this).appendTo($(this).data("Opener")).data("Opener", false);
                    });
                    $(this).hide(50, function() {
                        $(this).appendTo($(this).data("Opener")).data("Opener", false);
                    });
                };

            });
        };

    };
    //end ///Menu Builder

})(jQuery);